package goodbaby.dklt.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.FileUtil;
import com.classic.core.utils.ImageUtils;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.tgd.gbb.uikit.ui.widget.toast.LoadToast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import goodbaby.dklt.Const;
import goodbaby.dklt.R;
import goodbaby.dklt.customerview.AtlasSeeActivity;
import goodbaby.dklt.customerview.ImageLoaderUtil;
import goodbaby.dklt.customerview.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Jayden on 2016/4/26 17:22.
 *
 * @version V1.0
 * @Title: SendParentsCircleActivity
 * @Description: 发布家校互通页面
 */
public class SendParentsCircleActivity extends BaseActivity {

    private static final int REQUEST_IMAGE = 2;
    private final int PIC_MAX_LENGTH = 9;
    private ImageView addFriend;
    private String bitmapPath;
    private Context context;
    private ArrayList<String> currentPath = new ArrayList();
    private EditText edtContent;
    private LinearLayout friendLL;
    private ImageView ivBack;
    private List<FriendImageView> listFriend = new ArrayList();
    private ArrayList<String> mSelectPath;
    private int msgType;
    private ArrayList<String> selectedPictureAll = new ArrayList();
    private TextView tvSend;
    private TextView tvTitle;
    private Bitmap vedioBitmap;
    private File vedioFile;
    private String vedioFilePath;

    private void bitmapToPath() {
        vedioBitmap = ThumbnailUtils.createVideoThumbnail(vedioFilePath, 1);
        vedioBitmap = ThumbnailUtils.extractThumbnail(vedioBitmap, 96, 96, 2);
        File localFile2 = null;
        if (vedioBitmap != null) {
            File localFile1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/goodbaby/VedioImage/");
            if (!localFile1.exists())
                localFile1.mkdirs();
            bitmapPath = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/goodbaby/VedioImage/temp" + "_cropped" + ".jpg");
            localFile2 = new File(bitmapPath);
        }
        try {
            localFile2.createNewFile();
            FileOutputStream localFileOutputStream = new FileOutputStream(localFile2);
            vedioBitmap.compress(Bitmap.CompressFormat.JPEG, 50, localFileOutputStream);
            localFileOutputStream.flush();
            localFileOutputStream.close();
            ImageLoaderUtil.loadLocalUrl(bitmapPath, addFriend);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void changeImageToBitmap(ArrayList<String> images) {
        for (String image : images) {
            String theLarge;
            String theThumbnail = "";
            File imgFile;
            String imgName = FileUtil.getFileName(image);
            theLarge = image;
            if (imgName != null) {
                Bitmap bitmap = ImageUtils.loadImgThumbnail(SendParentsCircleActivity.this,
                        imgName,
                        MediaStore.Images.Thumbnails.MICRO_KIND);

                if (bitmap != null) {
                    String savePath = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/goodbaby/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }
                    String largeFileName = FileUtil.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 判断是否已存在缩略图
                    if (largeFileName.startsWith("thumb_")
                            && new File(largeFilePath).exists()) {
                        theThumbnail = largeFilePath;
                        imgFile = new File(theThumbnail);
                    } else {
                        // 生成上传的800宽度图片
                        String thumbFileName = "thumb_" + largeFileName;
                        theThumbnail = savePath + thumbFileName;
                        if (new File(theThumbnail).exists()) {
                            imgFile = new File(theThumbnail);
                        } else {
                            try {
                                // 压缩上传的图片
                                ImageUtils.createImageThumbnail(SendParentsCircleActivity.this,
                                        theLarge, theThumbnail, 800, 80);
                                imgFile = new File(theThumbnail);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                currentPath.add(theThumbnail);
            }

        }
    }

    private void notyPicChange() {
        if (selectedPictureAll.size() > 8) {
            addFriend.setVisibility(View.GONE);
        } else {
            addFriend.setVisibility(View.VISIBLE);
        }
    }

    private void submit() {
        String[] picPATHs = currentPath.toArray(new String[currentPath.size()]);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < currentPath.size() - 1; i++) {
            sb.append(ImageUtils.bitmapToBase64(ImageUtils.getBitmapByPath(currentPath.get(i))) + "#jpg");
            if (i < currentPath.size() - 2) {
                sb.append("|");
            }
        }

        System.err.print(sb.toString());

        if (picPATHs.length > 9) {
            ToastUtil.showToast(context, "最多上传9张图片哦~");
        } else if (StringUtil.isEmpty(edtContent.getText().toString().trim())) {
            ToastUtil.showToast(context, "发送内容不能为空哦");
        } else {
            if (edtContent.getText().toString().trim().length() > 140) {
                ToastUtil.showToast(context, "不能超过140个字");
            } else {
//						loadingDialog.show();
                showToast();
                tvSend.setEnabled(false);
                ActionHelp.gbbPubMsg(SendParentsCircleActivity.this, 1, edtContent.getText().toString().trim(), sb.toString(), new ObjectCallback<String>() {
                    @Override
                    public void onSuccess(String response) {
                        success();
                    }

                    @Override
                    public void onError(int code) {
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(context, "发布失败");
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        super.onError(code, errorMessage);
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(context, "发布失败");
                    }

                    @Override
                    public void onHttpError(int statusCode) {
                        super.onHttpError(statusCode);
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(context, "网络异常");
                    }

                    @Override
                    public Type getType() {
                        return new TypeToken<List<String>>() {
                        }.getType();
                    }
                });
            }
        }
    }


    private void vedioSubmit() {
        FileInputStream localFileInputStream = null;
        try {
            localFileInputStream = new FileInputStream(vedioFile);
            byte[] arrayOfByte = new byte[100 + (int) this.vedioFile.length()];
            String str = null;
            try {
                str = Base64.encodeToString(arrayOfByte, 0, localFileInputStream.read(arrayOfByte), 0);
            } catch (IOException e) {
                e.printStackTrace();
            }
            showToast();
            tvSend.setEnabled(false);
            ActionHelp.gbbPubMsg(this, 2, this.edtContent.getText().toString().trim(), str, new ObjectCallback<String>() {

                public void onError(int paramAnonymousInt) {
                    closeToast(-1);
                    tvSend.setEnabled(true);
                    ToastUtil.showToast(SendParentsCircleActivity.this.context, "发布失败");
                }

                public void onSuccess(String paramAnonymousString) {
                    success();
                }

                @Override
                public Type getType() {
                    return new TypeToken<String>() {
                    }.getType();
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    public int getLayoutResId() {
        return R.layout.activity_send_msg;
    }

    public void initView() {
        super.initView();
        msgType = getIntent().getIntExtra("msgType", 1);
        if (getIntent().getExtras().containsKey("vedioPath"))
            this.vedioFilePath = getIntent().getStringExtra("vedioPath");
        context = this;
        tvTitle = (TextView) findViewById(R.id.tv_common_title);
        tvTitle.setText("动态");
        tvSend = (TextView) findViewById(R.id.tv_common_leave_history);
        tvSend.setText("发送");
        tvSend.setVisibility(View.VISIBLE);
        tvSend.setOnClickListener(this);
        ivBack = (ImageView) findViewById(R.id.iv_common_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        addFriend = (ImageView) findViewById(R.id.iv_add_pic);
        addFriend.setOnClickListener(this);
        edtContent = (EditText) findViewById(R.id.et_sendmsg);
        friendLL = (LinearLayout) findViewById(R.id.ll_add_pic);
        if (msgType == 0) {
            vedioFile = new File(vedioFilePath);
            bitmapToPath();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                mSelectPath.removeAll(selectedPictureAll);
                selectedPictureAll.addAll(mSelectPath);
                for (String p : mSelectPath) {
                    FriendImageView friendImageView = new FriendImageView(p);
                    friendLL.addView(friendImageView.getFriendView(), friendLL.getChildCount() - 1);
                    listFriend.add(friendImageView);
                }
                changeImageToBitmap(mSelectPath);
                notyPicChange();

            }
        }

    }

    private void success() {
        closeToast(1);
        tvSend.setEnabled(true);
        ToastUtil.showToast(context, "发布成功");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setResult(RESULT_OK);
                finish();
            }
        }, 800);
    }

    private LoadToast toast;
    private final String loadingLable = "正在发布...";

    /**
     * LoadToast是否显示中
     */
    public boolean isToastShowing() {
        return null != toast && toast.isShowing();
    }

    /**
     * 显示LoadToast
     */
    public void showToast() {
        if (null == toast) {
            toast = new LoadToast(this);
            toast.setText(loadingLable);
            toast.setTranslationY(200).setBackgroundColor(Color.parseColor("#FFFFFF")).setProgressColor(Color.BLUE);
        }
        if (!isToastShowing()) toast.show();
    }

    /**
     * 关闭LoadToast
     *
     * @param type 0:关闭，1：成功，-1：错误
     */
    public void closeToast(int type) {
        if (null == toast) return;
        switch (type) {
            case -1:
                toast.error();
                break;
            case 0:
                toast.close();
                toast = null;
                break;
            case 1:
                toast.success();
                break;
        }
    }

    public void viewClick(View v) {
        super.viewClick(v);
        switch (v.getId()) {
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.tv_common_leave_history:
                //发布消息
                if (msgType == 0) {
                    vedioSubmit();
                } else {
                    submit();
                }
                break;
            case R.id.iv_add_pic:
                if (msgType == 0) {
                    Intent intent = new Intent(this, SurfaceActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("vedioUrl", this.vedioFilePath);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(this, MultiImageSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, PIC_MAX_LENGTH);
                    // 选择模式
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    // 默认选择
                    if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
                    }
                    startActivityForResult(intent, REQUEST_IMAGE);
                }
                break;
            default:
                break;
        }
    }

    private class FriendImageView
            implements
            View.OnClickListener {
        private View friendView;
        public ImageView friendImg;
        public ImageView deleteImg;

        public String imagePath = "";

        public FriendImageView(String imagePath) {
            friendView = LayoutInflater.from(context).inflate(R.layout.sendmsg_item_img, friendLL, false);
            friendImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_img);
            friendImg.setOnClickListener(this);
            deleteImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_delete);
            deleteImg.setOnClickListener(this);
            this.imagePath = imagePath;
            ImageLoaderUtil.loadLocalUrl(imagePath, friendImg);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.new_interation_center_user_publish_friend_item_delete:
                    remove();
                    break;
                case R.id.new_interation_center_user_publish_friend_item_img:
                    Intent atlasSeeIntent = new Intent(SendParentsCircleActivity.this, AtlasSeeActivity.class);
                    atlasSeeIntent.putExtra(Const.FROM_TYPE, Const.NI_FROM_LOCALURL);
                    atlasSeeIntent.putExtra(Const.NI_ATLASSEE_URL, selectedPictureAll);
                    atlasSeeIntent.putExtra(Const.NI_POSITION, listFriend.indexOf(this));
                    SendParentsCircleActivity.this.startActivity(atlasSeeIntent);
                    break;
            }

        }

        public void remove() {
            listFriend.remove(this);
            selectedPictureAll.remove(imagePath);
            friendLL.removeView(friendView);
            notyPicChange();
        }

        public View getFriendView() {
            return this.friendView;
        }

    }
}
